package room

import (
	"fmt"
	"qiniupkg.com/x/errors.v7"
	"sync"
)

var (
	roomMutex = new(sync.RWMutex)
	roomList  = make(map[string]IRoom)
)

var (
	errorRoomHasExist     = errors.New("room has been create")
	errorRoomNotExist     = errors.New("room not exist")
	errorRoomTypeNotMatch = errors.New("room not match expect")
	errorSessionExist     = errors.New("session exist")
	errorSessionNotExist  = errors.New("session not exist")
	errorStudentExist     = errors.New("student exist")
	errorStudentNotExist  = errors.New("student not exist")
)

//房间接口
type IRoom interface {
	Init()
	GC()
	GetAllUserIds() []int
	GetAllStudentIds() []int
	GetTeacherId() int
}

//enum
//区别房间
//正课，补课
//根据老师id,班级，课程id, 房间类型
func MakeRoomId(userId int, classId, courseId, roomType int) string {
	return fmt.Sprintf("room:%v:%v:%v:%v", userId, classId, courseId, roomType)
}

func FindRoom(roomId string) (IRoom, error) {
	roomMutex.RLock()
	defer roomMutex.RUnlock()
	if r, ok := roomList[roomId]; ok {
		return r, nil
	}
	return nil, errorRoomNotExist
}

func AddRoom(roomId string, room IRoom) error {
	roomMutex.Lock()
	defer roomMutex.Unlock()
	if _, ok := roomList[roomId]; ok {
		return errorRoomHasExist
	}
	roomList[roomId] = room
	return nil
}

func RemoveRoom(roomId string) error {
	roomMutex.Lock()
	defer roomMutex.Unlock()
	if _, ok := roomList[roomId]; !ok {
		return errorRoomNotExist
	}
	delete(roomList, roomId)
	return nil
}

func FindAIRoom(roomId string) (*AiRoom, error) {
	r, err := FindRoom(roomId)
	if err != nil {
		return nil, err
	}
	if a, ok := r.(*AiRoom); ok {
		return a, nil
	}
	return nil, errorRoomTypeNotMatch
}
